﻿using System;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SearchApp
{
    public class MainForm : Form
    {
        // 控件声明
        private TextBox txtKeyword;
        private Button btnSearch;
        private TextBox txtBaidu;
        private TextBox txtBing;
        private readonly HttpClient _httpClient = new HttpClient();

        public MainForm()
        {
            InitializeComponents();
            ConfigureHttpClient();
        }

        private void ConfigureHttpClient()
        {
            _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            _httpClient.Timeout = TimeSpan.FromSeconds(10);
        }

        private void InitializeComponents()
        {
            // 初始化控件
            txtKeyword = new TextBox();
            btnSearch = new Button();
            txtBaidu = new TextBox();
            txtBing = new TextBox();

            // 设置控件属性
            SuspendLayout();

          
            txtKeyword.Location = new System.Drawing.Point(12, 12);
            txtKeyword.Size = new System.Drawing.Size(400, 21);

            
            btnSearch.Location = new System.Drawing.Point(418, 10);
            btnSearch.Size = new System.Drawing.Size(75, 23);
            btnSearch.Text = "搜索";
            btnSearch.Click += btnSearch_Click;

           
            txtBaidu.Multiline = true;
            txtBaidu.ScrollBars = ScrollBars.Vertical;
            txtBaidu.Location = new System.Drawing.Point(12, 40);
            txtBaidu.Size = new System.Drawing.Size(400, 200);

            
            txtBing.Multiline = true;
            txtBing.ScrollBars = ScrollBars.Vertical;
            txtBing.Location = new System.Drawing.Point(12, 250);
            txtBing.Size = new System.Drawing.Size(400, 200);

            
            ClientSize = new System.Drawing.Size(500, 470);
            Controls.Add(txtKeyword);
            Controls.Add(btnSearch);
            Controls.Add(txtBaidu);
            Controls.Add(txtBing);
            Text = "搜索引擎结果抓取工具";

            ResumeLayout(false);
            PerformLayout();
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyword.Text;
            if (string.IsNullOrWhiteSpace(keyword))
            {
                MessageBox.Show("请输入搜索关键字");
                return;
            }

            txtBaidu.Clear();
            txtBing.Clear();

            try
            {
                var baiduTask = SearchAndDisplayAsync("baidu", keyword, txtBaidu);
                var bingTask = SearchAndDisplayAsync("bing", keyword, txtBing);

                await Task.WhenAll(baiduTask, bingTask);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索出错: {ex.Message}");
            }
        }

        private async Task SearchAndDisplayAsync(string engine, string keyword, TextBox textBox)
        {
            try
            {
                string html = await GetSearchResults(engine, keyword);
                string text = ExtractMainText(html);
                string result = text.Length > 200 ? text.Substring(0, 200) : text;

                textBox.Invoke((MethodInvoker)delegate {
                    textBox.Text = result;
                });
            }
            catch (Exception ex)
            {
                textBox.Invoke((MethodInvoker)delegate {
                    textBox.Text = $"错误: {ex.Message}";
                });
            }
        }

        private async Task<string> GetSearchResults(string engine, string keyword)
        {
            string engineLower = engine.ToLower();
            string url;

          
            switch (engineLower)
            {
                case "baidu":
                    url = $"https://www.baidu.com/s?wd={WebUtility.UrlEncode(keyword)}";
                    break;
                case "bing":
                    url = $"https://www.bing.com/search?q={WebUtility.UrlEncode(keyword)}";
                    break;
                default:
                    throw new ArgumentException("不支持的搜索引擎");
            }

            var response = await _httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }

        private string ExtractMainText(string html)
        {
            html = Regex.Replace(html, @"<script[^>]*>[\s\S]*?</script>", "");
            html = Regex.Replace(html, @"<style[^>]*>[\s\S]*?</style>", "");
            string text = WebUtility.HtmlDecode(Regex.Replace(html, @"<[^>]+>|&nbsp;", " "));
            return Regex.Replace(text, @"\s+", " ").Trim();
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}